/**
 * 版权所有(C)，上海勾芒信息科技，2017，所有权利保留。
 * 
 * 项目名：	cards-web
 * 文件名：	ReceiveTicketHandler.java
 * 模块说明：	
 * 修改历史：
 * 2017年6月1日 - Debenson - 创建。
 */
package com.alex.wechat.component.handler;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alex.wechat.component.account.entity.WxComponentAccountEntity;
import com.alex.wechat.component.account.service.WxComponentAccountServiceI;
import com.alex.wechat.core.handler.WxAccountType;
import com.alex.wechat.core.handler.WxHandler;
import com.alex.wechat.mp.config.WxConsts;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.message.bean.WxXmlMessage;
import me.chanjar.weixin.message.rule.WxMessageHandler;

/**
 * 微信服务推送component_verify_ticket事件处理器
 * 
 * @author Debenson
 * @since 0.1
 */
@WxHandler(infoType = WxConsts.INFO_TYPE_COMPONENT_VERIFY_TICKET,
    accountType = WxAccountType.COMPONENT)
public class VerifyTicketHandler implements WxMessageHandler {
  private static final Logger logger = LoggerFactory.getLogger(VerifyTicketHandler.class);

  @Autowired
  private WxComponentAccountServiceI compAccountService;

  @Override
  public String handle(WxXmlMessage wxMessage, Map<String, Object> context)
      throws WxErrorException {
    if (logger.isDebugEnabled()) {
      logger.debug("开始处理component_verify_ticket消息");
    }

    try {
      WxComponentAccountEntity account = compAccountService.getAccountByAppId(wxMessage.getAppId());
      account.setVerifyTicket(wxMessage.getComponentVerifyTicket());
      compAccountService.saveOrUpdate(account);
    } catch (Exception e) {
      logger.error("保存第三方平台的component_verify_ticket失败", e);
      throw new RuntimeException(e);
    }
    return WxConsts.SUCCESS_MSG;
  }

}
